package com.tt5.services.handlers.user

import com.tt5.services.bean.UserInfo
import com.tt5.services.error.ApiException
import com.tt5.services.vertx.sharedDbPool
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.coAwait
import io.vertx.sqlclient.Tuple

object UserInfoHandler {
  suspend fun get(ctx: RoutingContext) {
    val name = ctx.queryParam("name").firstOrNull() ?: throw ApiException(
        code = 400, content = "缺少参数：name"
    )
    val userInfo = ctx.sharedDbPool().withConnection { connection ->
      connection.preparedQuery(
        "select * from users where name=?"
      ).execute(Tuple.of(name))
    }.coAwait().firstOrNull()?.toJson()?.mapTo(UserInfo::class.java)
    if (userInfo == null) {
      throw ApiException(code = 400, error = "404", content = "用户 $name 未找到")
    }
    ctx.json(userInfo)
  }
}
